<template>
  <div class="app-container">
    <el-form :inline="true" :model="libID" class="demo-form-inline">
      <el-form-item label="查询题目">
        <el-input v-model="libID.libID" placeholder="请输入libID"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubLook"
          >查看题目</el-button
        >
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="onSubupopen(0,0,0)">上传题目</el-button>
      </el-form-item> -->
      <el-form-item label="上传">
        <input v-show="false" type="file" ref="upfile" @change="getFile($event)" />
        <el-button type="primary" @click="selectFile">选择文件</el-button>
        
      </el-form-item>
      <el-form-item><p>{{filename}}</p></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="upload">上传题目</el-button>
      </el-form-item>
    </el-form>
    
  <el-form :inline="true" :model="libID" class="demo-form-inline">
      <el-form-item label="删除题库">
        <el-input v-model="libID.libID" placeholder="请输入libID"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubdelete"
          >删除题库</el-button
        >
      </el-form-item>
    </el-form>
    
    
    <el-dialog
      :title="setting == 0 ? '上传题目' : '修改题目'"
      :visible.sync="dialogTableVisibleup"
      width="30%"
    >
      <el-form
        :model="upquestion"
        status-icon
        ref="upquestion"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="libID" prop="pass">
          <el-input
            type="text"
            v-model="upquestion.libID"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="ID" prop="pass">
          <el-input
            type="text"
            v-model="upquestion.id"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="题目" prop="pass">
          <el-input
            type="text"
            v-model="upquestion.content"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="选项" prop="pass">
          <el-input
            type="text"
            v-for="(item, index) in upquestion.options"
            :key="index"
            v-model="upquestion.options[index]"
            placeholder="依次填写选项"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="pass">
          <el-input
            type="text"
            v-model="upquestion.answer"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="onSubupload"
            >确定</el-button
          >
          <el-button size="mini" @click="Cancels">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- <el-dialog title="题目列表" :visible.sync="dialogTableVisiblelook" width="60%"> -->
    <el-table
      :data="
        qlist.slice((currentPage3s - 1) * pagesizes, currentPage3s * pagesizes)
      "
    >
      <el-table-column property="id" label="ID" width="150"></el-table-column>
      <el-table-column
        property="content"
        label="题目"
        width="300"
      ></el-table-column>
      <el-table-column label="选项" width="350">
        <template slot-scope="scope">
          <span v-for="(list, index) in scope.row.options" :key="index"
            >{{ index == 0 ? "1." : "" }}{{ index == 1 ? "2." : ""
            }}{{ index == 2 ? "3." : "" }}{{ index == 3 ? "4." : "" }}{{ list }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        property="answer"
        label="答案"
        width="150"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="onSubupopen(libID.libID, scope.$index)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleQDelate(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pages" v-if="qlist != ''">
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChanges"
          :current-page.sync="currentPage3s"
          :page-size="pagesizes"
          layout="prev, pager, next, jumper"
          :total="totals"
        >
        </el-pagination>
      </div>
    </div>
    <!-- </el-dialog> -->
  </div>
</template>

<script>
import Method from "@/utils/proto";
import { posts } from "@/api/api";
import XLSX from "xlsx";
import Error from '@/utils/error'
export default {
  data() {
    return {
      addnum: "",
      dialogTableVisiblelook: false,
      dialogTableVisibleup: false,
      filename:'',
      totals: 100,
      currentPage3s: 0,
      pagesizes: 15,
      qlist: [],
      libID: { libID: "" },
      setting: 1,
      upquestion: {
        id: "",
        options: ["", "", "", ""],
        content: "",
        answer: "",
        libID: "",
      },
      list:[]
    };
  },
  methods: {
    onSubdelete(){
      let roles = this.$store.getters.roles
        if(roles==10000000||roles==11000000||roles==11100000||roles=='00000000'||roles==11110000){
         this.$message({
           type:'warning',
           message:'没有权限执行此操作'
         })
         return
       }
      let libID = this.libID.libID
      let data = {
          method: Method.Method.MSG_AGENT_LIB_CLEAR_Q,
          token: this.$store.getters.token,
          libID:libID
      }
       this.$confirm(`此操作将题库为${libID}永久删除, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          posts(data)
            .then((res) => {
              if (res.result == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
               this.onSubLook()
              } else {
                this.$message({
                  type: "info",
                  message: "删除错误"+res.result ,
                });
              }
            })
            .catch();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getFile(e) {
      let roles = this.$store.getters.roles
        if(roles==10000000||roles==11000000||roles==11100000||roles=='00000000'){
         this.$message({
           type:'warning',
           message:'没有权限执行此操作'
         })
         return
       }
      const that = this
      var files = e.target.files;
      this.filename = files[0].name
      var fileReader = new FileReader();
      fileReader.onload = function (ev) {
        try {
          var data = ev.target.result,
            workbook = XLSX.read(data, {
              type: "binary",
            }), // 以二进制流方式读取得到整份excel表格对象
            elements = []; // 存储获取到的数据
        } catch (ex) {
          // /return;
        }

        // 表格的表格范围，可用于判断表头是否数量是否正确
        var fromTo = "";
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]["!ref"];
            elements = elements.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            );
            break; // 如果只取第一张表，就取消注释这行
          }
        }
       
        that.list = elements;
      };
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files[0]);
      // }
    },
    upload(){
      let roles = this.$store.getters.roles
        if(roles==10000000||roles==11000000||roles==11100000||roles=='00000000'){
         this.$message({
           type:'warning',
           message:'没有权限执行此操作'
         })
         return
       }
      const that = this
      let list = that.list
      var element = []
      for (let index = 0; index < list.length; index++) {
         element[index] = Object.values(list[index])    
      }
      let data = {
        method: Method.Method.MSG_AGENT_LIB_UPLOAD_Q,
        token: this.$store.getters.token,
        list:element
      };
      if(list==''){
        this.$message({
          type:'warning',
          message:'请选择文件'
        })
        return
      }
      posts(data).then((res) => {
    })
    .catch();
      
    },
    selectFile(){
      this.$refs.upfile.click()
    },
    handleCurrentChanges(val) {
      this.currentPage3s = val;
    },
    Cancels() {
      this.dialogTableVisibleup = false;
    },

    onSubupopen(idss, index, setting) {
      let roles = this.$store.getters.roles
        if(roles==10000000||roles==11000000||roles==11100000||roles=='00000000'||roles==11110000){
         this.$message({
           type:'warning',
           message:'没有权限执行此操作'
         })
         return
       }
      let indexs = index ? index : 0;
      let ids = idss ? idss : 0;
      this.dialogTableVisibleup = true;
      this.setting = setting;
      if (setting != 0) {
        this.setting = setting;
        this.upquestion.id = this.qlist[indexs].id;
        this.upquestion.content = this.qlist[indexs].content;
        this.upquestion.answer = this.qlist[indexs].answer;
        this.upquestion.options = this.qlist[indexs].options;
        this.upquestion.libID = ids;
      }
    },
    handleQDelate(qid) {
      const that = this;
      let roles = this.$store.getters.roles
        if(roles==10000000||roles==11000000||roles==11100000||roles=='00000000'||roles==11110000){
         this.$message({
           type:'warning',
           message:'没有权限执行此操作'
         })
         return
       }
      let data = {
        method: Method.Method.MSG_AGENT_DELETE_Q,
        token: this.$store.getters.token,
        libid: this.upquestion.libID,
        qid:qid
      };

      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          posts(data)
            .then((res) => {
              if (res.result == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
               this.onSubLook()
              } else {
                this.$message({
                  type: "info",
                  message: "删除错误"+res.result ,
                });
              }
            })
            .catch();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onSubupload() {
      const that = this;
      let data = that.upquestion;
      data.method = Method.Method.MSG_AGENT_LIB_UPDATE_Q;
      data.token = this.$store.getters.token;
      posts(data)
        .then((res) => {
          if(res.result == 0){
             this.$message({
              type: 'success',
              message: '修改成功',
            });
           that.libID.libID = that.upquestion.libID;
          that.onSubLook();
          }else{
            this.$message({
              type: 'error',
              message: Error.getErrorMessage(res.result),
            });
         }
          that.dialogTableVisiblelook = true;
        })
        .catch();
    },
    onSubLook() {
      let data = {
        method: Method.Method.MSG_AGENT_LIB_Q_LIST,
        libID: this.libID.libID,
        token: this.$store.getters.token,
      };
      posts(data)
        .then((res) => {
          this.dialogTableVisiblelook = true;
          this.qlist = res.list;
          this.totals = res.list.length;
        })
        .catch();
    },
    Cancel() {
      this.dialogFormVisiblea = false;
      this.dialogFormVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.pages {
  width: 100%;
  margin-top: 2%;
  display: flex;
  justify-content: center;
}
</style>
